<template>
  <el-card>
    <div class="nav-wrap">
      <div class="title">订单管理</div>
    </div>
    <div class="query-form">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="姓名" size="mini">
          <el-input v-model="queryForm.name" placeholder="请输入姓名" size="mini" />
        </el-form-item>
        <el-form-item label="手机号" size="mini">
          <el-input v-model="queryForm.phone" placeholder="请输入手机号" size="mini" />
        </el-form-item>
        <el-form-item label="券码" size="mini">
          <el-input v-model="queryForm.code" placeholder="请输入券码" size="mini" />
        </el-form-item>
        <el-form-item label="状态" size="mini">
          <el-select v-model="queryForm.orderStatus" placeholder="请选择状态" size="mini">
            <el-option v-for="item in statusList" :key="item.key" :label="item.name" :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item size="mini">
          <el-button type="primary" @click="onQuery" size="mini">查询</el-button>
          <el-button @click="onReset" size="mini">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="operate-wrap">
      <el-button type="primary" icon="el-icon-download" @click="exportExcel" size="mini">导出Excel</el-button>
      <el-button type="success" icon="el-icon-copy-document" @click="multiRemark" size="mini">批量备注</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="multiDelete" size="mini">批量删除</el-button>
    </div>
    <div class="table-wrap">
      <el-table
        :data="tableData"
        style="width: 100%"
        header-row-class-name="table-header"
        :span-method="spanMethod"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="orderBusinessId" label="订单编号">
          <!-- <template slot-scope="{ row }"> -->
          <!-- 如果当前行有extra属性，表示是新增的单元格 -->
          <!-- <div v-if="row.extra" class="extraRowCtWrap" :class="{ hidden: row.isHidden }">
              <el-timeline>
                <el-timeline-item
                  v-for="(item, index) in row.timestampList"
                  :key="index"
                  :type="index <= row.status - 1 ? 'primary' : ''"
                  :icon="index <= row.status - 1 ? 'el-icon-check' : ''"
                  :timestamp="item.timestamp"
                >
                  {{ item.name }}
                </el-timeline-item>
              </el-timeline>
            </div>
            <div v-else>{{ row.orderBusinessId }}</div>
          </template> -->
        </el-table-column>
        <el-table-column prop="code" label="券码"> </el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="address" label="收获地址"></el-table-column>
        <el-table-column prop="userRemark" label="用户备注"></el-table-column>
        <el-table-column prop="statusName" label="状态">
          <!-- <template slot-scope="{ row }">
            <div class="statusWrap" @click="toggleTimeline(row)">
              {{ row.statusName }}
              <i class="el-icon-arrow-right rightArrow" :class="{ active: !row.isHidden }"></i>
            </div>
          </template> -->
        </el-table-column>
        <el-table-column prop="orderRemark" label="备注"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <div style="display: flex; flex-wrap: wrap; gap: 10px">
              <el-button type="primary" @click="openDialog(scope.row, 'status')" size="mini">修改状态</el-button>
              <el-button
                type="primary"
                @click="openDialog(scope.row, 'remark')"
                size="mini"
                icon="el-icon-copy-document"
                style="margin-left: 0px"
                >备注</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-wrap">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryForm.showCount"
        :layout="paginationLayoutStr"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog :title="dialogFormTitle" width="400px" :visible.sync="dialogVisible">
      <el-form ref="dialogForm" label-width="120px" class="dialogForm">
        <el-form-item prop="status" v-if="dialogFormType === 'updateStatus'">
          <el-select v-model="dialogForm.status" placeholder="请选择状态">
            <el-option v-for="item in statusListInDialog" :key="item.key" :label="item.name" :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="remark" v-else>
          <el-input type="textarea" autosize placeholder="请输入备注" v-model="dialogForm.remark"> </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
        <el-button @click="cancelEdit">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="批量备注" width="400px" :visible.sync="multiRemarkDialogVisible">
      <el-form ref="dialogForm" :model="dialogForm" label-width="120px" class="dialogForm">
        <el-form-item prop="remark">
          <el-input type="textarea" autosize placeholder="请输入备注" v-model="multiRemarkCt"> </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmMultiRemark">确 定</el-button>
        <el-button @click="cancelMultiRemark">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  listOrders, updateOrderStatus, exportOrderList, updateOrderRemark, batchDeleteOrder,
} from '@/api/index';

export default {
  name: 'order',
  data() {
    return {
      tableData: [],
      statusList: [
        {
          key: '1',
          name: '待发货',
        },
        {
          key: '2',
          name: '已发货',
        },
        {
          key: '3',
          name: '已签收',
        },
      ],
      statusListInDialog: [],
      queryForm: {
        name: '',
        phone: '',
        code: '',
        orderStatus: '',
        currentPage: 1,
        showCount: 10,
      },
      total: 0,
      dialogFormType: '', // 取值 updateStatus addRemark updateRemark
      dialogForm: {
        status: '',
        remark: '',
      },
      editCodeId: '',
      editOrderId: '',
      dialogVisible: false,
      paginationLayoutStr: 'total, sizes, prev, pager, next, jumper',
      multiDeleteIds: [],
      multiRemarkCt: '',
      multiRemarkDialogVisible: false,
    };
  },
  created() {
    this.getList();
    if (this.$store.state.screenWidth < 990) {
      this.paginationLayoutStr = 'total, prev, next';
    }
  },
  computed: {
    exportBtnVisile() {
      return this.tableData.length > 0;
    },
    dialogFormTitle() {
      let tmpTitle;
      if (this.dialogFormType === 'updateStatus') {
        tmpTitle = '状态更新';
      } else if (this.dialogFormType === 'addRemark') {
        tmpTitle = '添加备注';
      } else if (this.dialogFormType === 'updateRemark') {
        tmpTitle = '修改备注';
      }
      return tmpTitle;
    },
  },
  methods: {
    onQuery() {
      console.log(this.queryForm);
      this.getList();
    },
    onReset() {
      this.queryForm = {
        name: '',
        phone: '',
        code: '',
        orderStatus: '',
        currentPage: 1,
        showCount: 10,
      };
      this.getList();
    },
    handleSizeChange(e) {
      this.queryForm.showCount = e;
      this.getList();
    },
    handleSelectionChange(selection) {
      this.multiDeleteIds = selection.map((item) => item.orderId);
      console.log(this.multiDeleteIds);
    },
    handleCurrentChange(e) {
      this.queryForm.currentPage = e;
      this.getList();
    },
    openDialog(e, dialogType) {
      if (dialogType === 'status') {
        // 更新状态
        this.dialogFormType = 'updateStatus';

        this.editCodeId = e.couponId;
        this.editOrderId = e.orderId;
        this.dialogForm = {
          status: '',
        };
        this.statusListInDialog = this.statusList.filter((item) => item.key > e.status);
        if (this.statusListInDialog.length === 0) {
          this.$message({
            message: '当前状态已经是最后一个状态!',
            type: 'warning',
          });
          return;
        }
        console.log(this.statusListInDialog);
        this.dialogVisible = true;
      } else {
        // 添加/更新备注
        this.editOrderId = e.orderId;
        if (e.orderRemark) {
          this.dialogFormType = 'updateRemark';
          this.dialogForm = {
            remark: e.orderRemark,
          };
        } else {
          this.dialogFormType = 'addRemark';
          this.dialogForm = {
            remark: '',
          };
        }
        this.dialogVisible = true;
      }
    },
    confirmEdit() {
      if (this.dialogFormType === 'updateStatus') {
        // 更新状态
        if (!this.dialogForm.status) {
          this.$message({
            message: '请选择状态!',
            type: 'warning',
          });
          return;
        }
        this.dialogVisible = false;
        setTimeout(() => {
          console.log(this.dialogForm, this.editCodeId, this.editOrderId);
          const tmpStatusName = this.statusList.find((item) => item.key === this.dialogForm.status).name;
          // 询问是否确认将状态修改成
          this.$confirm(`是否确认将状态修改成“${tmpStatusName}”?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              updateOrderStatus({
                orderId: this.editOrderId,
                couponId: this.editCodeId,
                type: this.dialogForm.status,
              })
                .then((res) => {
                  console.log(res);
                  this.$message({
                    message: '修改成功',
                    type: 'success',
                  });
                  this.getList();
                })
                .catch((err) => {
                  console.log(err);
                  this.$message({
                    message: '修改失败',
                    type: 'error',
                  });
                });
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消修改',
              });
            });
        }, 300);
      } else {
        // 添加/更新备注
        if (!this.dialogForm.remark) {
          this.$message({
            message: '请输入备注!',
            type: 'warning',
          });
          return;
        }
        updateOrderRemark({
          orderId: this.editOrderId,
          orderRemark: this.dialogForm.remark,
        })
          .then((res) => {
            console.log(res);
            this.$message({
              message: `${this.dialogFormTitle}成功`,
              type: 'success',
            });
            this.dialogVisible = false;
            this.getList();
          })
          .catch((err) => {
            console.log(err);
            this.dialogVisible = false;
            this.$message({
              message: `${this.dialogFormTitle}失败`,
              type: 'error',
            });
          });
      }
    },
    cancelEdit() {
      this.dialogVisible = false;
      this.dialogFormType = '';
    },
    getList() {
      listOrders({
        pageNum: this.queryForm.currentPage,
        pageSize: this.queryForm.showCount,
        receiveName: this.queryForm.name,
        receivePhone: this.queryForm.phone,
        couponCode: this.queryForm.code,
        orderStatus: this.queryForm.orderStatus,
      }).then((res) => {
        console.log(res);
        this.tableData = res.data.resData.list.map((item) => {
          const tmpTimestampList = [
            {
              orderStatus: '1',
              name: '已兑换',
              timestamp: '',
            },
            {
              orderStatus: '2',
              name: '已发货',
              timestamp: '',
            },
            {
              orderStatus: '3',
              name: '已签收',
              timestamp: '',
            },
          ];
          // timestampList: this.updateTableData(item.timeInfos, tmpTimestampList),
          const data = {
            orderBusinessId: item.orderBuisnessId,
            couponId: item.couponId,
            orderId: item.orderId,
            code: item.couponCode,
            name: item.receiveName,
            phone: item.receivePhone,
            address: item.receiveAddress,
            userRemark: item.userRemark,
            // isHidden: true,
            status: item.orderStatus,
            statusName: this.statusList.find((status) => status.key === item.orderStatus).name,
            orderRemark: item.orderRemark,
          };
          // return [data].concat({
          //   extra: true,
          //   isHidden: true,
          //   status: item.orderStatus,
          //   timestampList: this.updateTableData(item.timeInfos, tmpTimestampList),
          // });
          return data;
        });
        // .flat();
        console.log('tableData:', this.tableData);
        this.total = res.data.resData.total;
      });
    },
    exportExcel() {
      if (!this.exportBtnVisile) {
        this.$message.error('没有可导出的数据!');
        return;
      }
      exportOrderList({
        pageNum: this.queryForm.currentPage,
        pageSize: this.queryForm.showCount,
        receiveName: this.queryForm.name,
        receivePhone: this.queryForm.phone,
        couponCode: this.queryForm.code,
        orderStatus: this.queryForm.orderStatus,
      }).then((res) => {
        console.log(res);
        // 创建Blob对象
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' });
        // 创建URL
        const url = URL.createObjectURL(blob);
        // 创建a标签
        const a = document.createElement('a');
        a.href = url;
        a.download = '订单.xlsx'; // 指定下载文件名
        // 触发点击事件
        a.click();
      });
    },
    updateTableData(timeInfos, tableData) {
      // 如果timeInfos为空，直接返回tableData
      if (timeInfos.length === 0) return tableData;
      // 定义一个变量i，表示timeInfos的索引，初始为最后一个元素
      let i = timeInfos.length - 1;
      // 定义一个变量count，表示tableData中还未赋值的元素个数，初始为tableData的长度
      let count = tableData.length;
      // 使用一个while循环，当i大于等于0且count大于0时，继续循环
      while (i >= 0 && count > 0) {
        // 获取timeInfos的第i个元素
        const current = timeInfos[i];
        // 遍历tableData，找到orderStatus和current.type相同的元素
        tableData.forEach((item) => {
          if (item.orderStatus === current.type) {
            // 如果该元素的timestamp还未赋值，就更新为current.recordTime，并将count减一
            if (!item.timestamp) {
              item.timestamp = current.recordTime;
              count--;
            }
          }
        });
        // 将i减一，继续遍历下一个元素
        i--;
      }
      // 返回更新后的tableData
      return tableData;
    },
    spanMethod({
      row, column, rowIndex, columnIndex,
    }) {
      if (row.extra) {
        if (columnIndex === 0) {
          return [1, 7];
        }
        return [0, 0];
      }
      return [1, 1];
    },
    toggleTimeline(row) {
      console.log(row, this.tableData);
      const tmpIndex = this.tableData.findIndex((item) => item.orderBusinessId === row.orderBusinessId);
      this.tableData[tmpIndex].isHidden = !this.tableData[tmpIndex].isHidden;
      this.tableData[tmpIndex + 1].isHidden = this.tableData[tmpIndex].isHidden;
    },
    multiRemark() {
      if (this.multiDeleteIds.length === 0) {
        this.$message.error('请选择要批量备注的券码');
        return;
      }
      this.multiRemarkDialogVisible = true;
    },
    requestMultiRemark() {
      const asyncTask = [];
      this.multiDeleteIds.forEach((id) => {
        asyncTask.push(
          updateOrderRemark({
            orderId: id,
            orderRemark: this.multiRemarkCt,
          }),
        );
      });
      Promise.all(asyncTask)
        .then((res) => {
          console.log(res);
          this.$message.success('批量备注成功!');
          this.multiRemarkDialogVisible = false;
          this.getList();
        })
        .catch((err) => {
          console.log(err);
          this.$message.error('批量备注失败!');
        });
    },
    confirmMultiRemark() {
      if (!this.multiRemarkCt) {
        this.$message.error('请输入批量备注的内容');
        return;
      }
      this.requestMultiRemark();
    },
    cancelMultiRemark() {
      this.multiRemarkCt = '';
      this.multiRemarkDialogVisible = false;
    },
    /**
     * 批量删除订单
     */
    multiDelete() {
      if (this.multiDeleteIds.length === 0) {
        this.$message.error('请选择要删除的订单');
        return;
      }
      this.$confirm('是否删除选中的订单', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          console.log('确定删除');
          batchDeleteOrder({
            orderIds: this.multiDeleteIds.join(','),
          })
            .then((res) => {
              console.log(res);
              if (res.data.code === '000000') {
                this.$message.success('删除成功!');
                this.getList();
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((err) => {
              console.log(err);
              this.$message.error('删除失败!');
            });
        })
        .catch(() => {
          console.log('取消删除');
        });
    },
  },
};
</script>
<style scoped lang="less">
.nav-wrap {
  display: flex;
  align-items: center;
  height: 40px;

  .title {
    padding-left: 18px;
    height: 26px;
    font-size: 19px;
    font-weight: 500;
    color: #3b3c3d;
    line-height: 26px;
    position: relative;
    top: -20px;
    left: -20px;

    &::after {
      content: '';
      position: absolute;
      left: 0;
      width: 6px;
      height: 100%;
      background: #1e87f0;
      border-radius: 3px;
    }
  }
}

.operate-wrap {
  margin-bottom: 20px;
}

.table-wrap::v-deep {
  flex: 1;
  height: 100%;

  .table-header {
    th {
      color: rgba(0, 0, 0, 0.85);
      background-color: #fafafa;
    }

    .cell {
      font-size: 13px;
      color: rgba(0, 0, 0, 0.65);
    }

    .column-header {
      font-weight: bold;
    }
  }

  .padding-left {
    padding-left: 20px;
  }

  .el-timeline {
    display: flex;
    justify-content: center;

    .el-timeline-item {
      margin-right: 10px;
      padding-bottom: 20px;
      width: 30%;

      &:nth-child(3) {
        width: 15%;
      }

      .el-timeline-item__tail {
        border-left: 0px solid transparent;
        width: 100%;
        top: 7px;
        height: 2px;
        background-color: #e4e7ed;
      }

      .el-timeline-item__node--normal {
        width: 16px;
        height: 16px;
      }

      .el-timeline-item__wrapper {
        padding-left: 0px;
        padding-top: 4px;
        top: 15px;
      }
    }
  }

  .el-table__row:nth-child(odd) {
    .el-table__cell {
      border-bottom: unset;
    }
  }

  .cell {
    .extraRowCtWrap {
      transition: all 0.3s ease-in-out;
      height: 80px;

      &.hidden {
        height: 0;
        overflow: hidden;
        transition: all 0.3s ease-in-out;
      }
    }
  }
}

.pagination-wrap {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
}

.statusWrap {
  cursor: pointer;

  .rightArrow {
    margin-left: 5px;
    transition: all 0.3s ease-in-out;
    transform: rotate(0deg);

    &.active {
      transform: rotate(90deg);
    }
  }
}
</style>
